package com.njwb.day15.zqzb.sql;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class Util {
    public static void addMember(int no,String name,String from) {
        String sql = "INSERT INTO c (no,name,froms) VALUES (?, ?, ?)";

        try (Connection conn = Driver.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, no);
            ps.setString(2, name);
            ps.setString(3, from);


            int rows = ps.executeUpdate();
            System.out.println("插入成功，影响行数：" + rows);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void queryMembers() {
        String sql = "SELECT * FROM c";

        try (Connection conn = Driver.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql);
             ResultSet rs = ps.executeQuery()) {

            while (rs.next()) {
                System.out.println("ID: " + rs.getInt("no") +
                        ", 用户名: " + rs.getString("name") +
                        ", 来自: " + rs.getString("froms"));
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void updateMemberPhone(int id, String name ,String from) {
        String sql = "UPDATE c SET name = ? ,froms=? WHERE no = ?";

        try (Connection conn = Driver.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setString(1, name);
            ps.setString(2, from);
            ps.setInt(3,id);

            int rows = ps.executeUpdate();
            System.out.println("更新成功，影响行数：" + rows);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void deleteMember(int id) {
        String sql = "DELETE FROM c WHERE no = ?";

        try (Connection conn = Driver.getConnection();
             PreparedStatement ps = conn.prepareStatement(sql)) {

            ps.setInt(1, id);
            int rows = ps.executeUpdate();
            System.out.println("删除成功，影响行数：" + rows);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static boolean select(int no) {
        String sql = "SELECT * FROM c WHERE no = ?";
        try (Connection connection = Driver.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement(sql)) {

            preparedStatement.setInt(1, no);
            ResultSet rs = preparedStatement.executeQuery();


            if (rs.next()) {
                System.out.println("学号："+rs.getInt("no")+"、姓名："+rs.getString("name")+"、来自："+rs.getString("froms"));
                return false;
            } else {
                return true;
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

}

